<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('监控科目/指标')" prop="keyCode">
            <treeselect v-model="form.keyCode" :options="sysKeyOptions" :disable-branch-nodes="true" :placeholder="$t('监控科目/指标')" @select="selectTree">
              <label slot="option-label" slot-scope="{ node, shouldShowCount, count, labelClassName, countClassName }" :class="labelClassName">
                {{ $t(node.label) }}
                <span v-if="shouldShowCount" :class="countClassName">({{ count }})</span>
              </label>
              <label slot="value-label" slot-scope="{ node }">
                {{ $t(node.label) }}
              </label>
            </treeselect>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('上下行预警')" prop="warmUpdown">
            <el-select v-model="form.warmUpdown" :placeholder="$t('上下行预警')">
              <el-option v-for="dict in riskTypeOptions" :key="dict.dictValue" :label="$t(dict.dictLabel)" :value="dict.dictValue" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('预警线')" prop="warnLine">
            <Money v-model="form.warnLine" :placeholder="$t('预警线')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('警报线')" prop="alarmLine">
            <Money v-model="form.alarmLine" :placeholder="$t('警报线')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('关键条款')" prop="termsId">
            <el-select v-model="form.termsId" filterable clearable :placeholder="$t('请选择')">
              <el-option v-for="item in termsOptions" :key="item.id" :label="item.label" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('最新值')" prop="latestValue">
            <Money v-model="form.latestValue" :placeholder="$t('最新值')" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('备注')" prop="remark">
            <el-input v-model="form.remark" type="textarea" :placeholder="$t('备注')" show-word-limit maxlength="2000" />
          </el-form-item>
        </el-col>
      </el-row>

      <div class="area-header">
        <span class="area-header-title">{{ $t('指标报警信息') }}</span>
      </div>
      <el-table :data="form.riskDetails" border class="formTable" style="width: 98%;">
        <el-table-column :label="$t('财报日期')" align="center" prop="year">
          <template slot-scope="scope">
            <span>{{ scope.row.year + '-' + $t(scope.row.typeLabel) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('数据来源')" align="center" prop="dataSource" :formatter="dataSourceFormat" />
        <el-table-column :label="$t('本期值')" align="center" prop="keyValue">
          <template slot-scope="scope">
            <span>{{ formattedNumber(scope.row.keyValue) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('报警级别')" align="center" prop="riskType">
          <template slot-scope="scope">
            <span v-if="scope.row.riskType === 'red'" class="risk-type-red" />
            <span v-if="scope.row.riskType === 'yellow'" class="risk-type-yellow" />
          </template>
        </el-table-column>
        <el-table-column :label="$t('是否处理')" align="center" prop="isHandel">
          <template slot-scope="scope">
            <el-form-item>
              <el-select v-model="scope.row.isHandel" :placeholder="$t('是否处理')">
                <el-option v-for="item in isHandelOptions" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue" />
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('操作')" align="center" width="80" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button :v-bind:v-has-permi="['company:pcw:remove']" size="mini" type="text" icon="el-icon-delete" @click="delRowDetails(scope.$index,scope.row)">{{ $t('删除') }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="tol">
        <el-button size="small" type="primary" @click="getPcwDataBaseRisk">{{ $t("刷新指标信息") }}</el-button>
      </div>
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存，保存并启动流程，取消 三个按钮-->
      <SaveBtn has-permi="company:pcw" />
    </div>

  </div>
</template>

<script>
import {
  savePcwRiskMonitor,
  getPcwRiskMonitor,
  getRiskDetails,
  listPcwTerms
} from '@/api/company/pcw/pcwRiskMonitor'
import {
  listSubjectTree
} from '@/api/company/pcw/pcwTempSubject'
import {
  delPcwRiskDetails
} from '@/api/company/pcw/pcwRiskDetails'
import Treeselect from '@riophae/vue-treeselect'

export default {
  components: {
    Treeselect
  },
  props: {
    companyId: {
      type: String,
      required: true,
      default: ''
    }
  },
  data() {
    var checkAlarmLine = (rule, value, callback) => {
      console.info(this.form)
      if (value === '') {
        callback(new Error('必填信息'))
      } else if (value === this.form.warnLine) {
        callback(new Error('预警线和警报线不能相等'))
      } else if (this.form.warmUpdown === 'up' && value < this.form.warnLine) {
        callback(new Error('上行预警 警报线不能小于预警线'))
      } else if (this.form.warmUpdown === 'down' && value > this.form.warnLine) {
        callback(new Error('下行预警 警报线不能大于预警线'))
      } else {
        callback()
      }
    }
    return {
      // 表单参数
      form: {
        // 指标监控详情
        riskDetails: [],
        // 警报线默认值
        alarmLine: 0,
        // 报警线默认值
        warnLine: 0
      },
      // 所有关键条款
      termsOptions: [],
      // 遮罩层
      loading: false,
      // 表单校验
      rules: {
        keyCode: [{
          required: true,
          message: this.$t('必填信息'),
          trigger: 'change'
        }],
        warmUpdown: [{
          required: true,
          message: this.$t('必填信息'),
          trigger: 'blur'
        }],
        alarmLine: [{
          required: true,
          validator: checkAlarmLine,
          trigger: 'blur'
        }],
        warnLine: [{
          required: true,
          message: this.$t('必填信息'),
          trigger: 'blur'
        }]
      },
      // 预警类型
      riskTypeOptions: [],
      // 查询财务指标参数
      queryParams: {
        companyId: this.companyId,
        // 监控财务指标
        keyCode: '',
        // 上下行预警
        warmUpdown: '',
        // 预警线
        alarmLine: '',
        // 报警线
        warnLinie: ''
      },
      // 查询科目下拉框参数
      querySubject: {
        companyId: this.companyId
      },
      // 科目类型
      sysKeyOptions: [],
      isHandelOptions: [],
      dataSourceOptions: []
    }
  },
  created() {
    this.getDicts('pcw_data_source').then(response => {
      this.dataSourceOptions = response.data
    })
    // 根据选择的tableName,获取下面的默认指标
    listSubjectTree(this.querySubject).then(response => {
      const item = response.rows
      this.diGuiTree(item)
      this.sysKeyOptions = item
    })
    this.getDicts('risk_monitor_type').then(response => {
      this.riskTypeOptions = response.data
    })
    this.getDicts('sys_yes_no').then(response => {
      this.isHandelOptions = response.data
    })
    // 获取所有公司列表
    listPcwTerms(this.queryParams).then(response => {
      this.termsOptions = response.rows
    })
  },
  methods: {
    // 初始化数据
    init(data) {
      this.loading = true
      if (data !== null && data.id !== undefined) {
        getPcwRiskMonitor(data.id).then(response => {
          this.form = response.data
          // this.form.resourceId = this.form.keyCode
          this.loading = false
        })
      } else {
        this.reset()
        this.loading = false
      }
    },
    // 递归函数的具体写法：
    diGuiTree(item) {
      item.forEach(item => {
        if (item.children === '' || item.children === undefined || item.children === null || item.children.length === 0) {
          delete item.children
        } else {
          this.diGuiTree(item.children)
        }
      })
    },
    selectTree(val) {
      this.form.keyCode = val.id
      this.form.keyName = val.keyName
    },
    // 根据指标和上下行预警获取相关财务指标
    getPcwDataBaseRisk() {
      var warmUpdown = this.form.warmUpdown
      var keyCode = this.form.keyCode
      var alarmLine = this.form.alarmLine
      var warnLine = this.form.warnLine
      if (warmUpdown === '' || warmUpdown === undefined) {
        return false
      }

      if (keyCode === '' || keyCode === undefined) {
        return false
      }
      this.$set(this.form, 'riskDetails', [])
      this.queryParams.keyCode = keyCode
      this.queryParams.warmUpdown = warmUpdown
      this.queryParams.alarmLine = alarmLine
      this.queryParams.warnLine = warnLine

      getRiskDetails(this.queryParams).then(response => {
        this.$set(this.form, 'riskDetails', response.rows)
      })
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        companyId: this.companyId,
        resourceId: undefined,
        keyName: undefined,
        warmUpdown: undefined,
        alarmLine: undefined,
        warnLine: undefined,
        alarmCount: undefined,
        warmCount: undefined,
        handleCount: undefined,
        latestValue: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        delFlag: undefined,
        remark: undefined
      }
      this.resetForm('form')
    },
    // 取消按钮
    cancel() {
      this.$parent.$parent.formOpen = false
      this.$parent.$parent.reset()
    },
    // 关闭form页面
    closeForm() {
      // 关闭form页面遮罩层
      this.loading = false
      // 关闭form页面
      this.$parent.$parent.formOpen = false
      // 刷新list页面
      this.$parent.$parent.getList()
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.loading = true
          // this.form.companyId = this.$route.query.companyId
          savePcwRiskMonitor(this.form).then(response => {
            if (response.code === 200) {
              this.msgSuccess(this.$t('保存成功'))
              this.closeForm()
            } else {
              this.msgError(response.msg)
            }
            this.loading = false
          }).catch(() => {
            this.loading = false
          })
        } else {
          this.locationError(document)
        }
      })
    },
    // 删除监控指标
    delRowDetails(index, row) {
      const id = row.id
      if (this.form.id !== undefined && this.form.id !== '' && this.form.id != null) {
        this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
            confirmButtonText: this.$t('确定'),
            cancelButtonText: this.$t('取消'),
            type: 'warning'
          })
          .then(function() {
            return delPcwRiskDetails(id)
          }).then(() => {
            this.form.riskDetails.splice(index, 1)
            return this.msgSuccess(this.$t('删除成功'))
          })
          .catch(function() {})
      } else {
        this.form.riskDetails.splice(index, 1)
        this.msgSuccess(this.$t('删除成功'))
      }
    },
    dataSourceFormat(row) {
      return this.selectDictLabel(this.dataSourceOptions, row.dataSource)
    },
    /**
     * 金额增加千分位
     * @param {*} val
     * @returns
     */
    formattedNumber(val) {
      val = this.formatMoney(val)
      if (val != null && !isNaN(Number(val))) {
        if (typeof val === 'string') {
          return parseFloat(val).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
        } else if (typeof val === 'number') {
          return val.toLocaleString('en-US', {
            style: 'decimal',
            minimumFractionDigits: 2,
            maximumFractionDigits: 2
          })
        }
      } else {
        return val
      }
    },
    formatMoney(value) {
      if (value) {
        if (!isNaN(value)) {
          return parseFloat(value).toFixed(2)
        } else {
          return value
        }
      } else {
        return '0.00'
      }
    }
  }
}
</script>
